var moment = require('moment')
var WXBizDataCrypt = require("../public/WXBizDataCrypt")

module.exports = function* (ctx) {
    const iv = ctx.request.body.iv
    const code = ctx.request.body.code
    const encryptedData = ctx.request.body.encryptedData
    const appID = this.app.config.app.appID
    const appSecret = this.app.config.app.appSecret
    var api = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appID + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code"
    const res = yield ctx.curl(api, {
        dataType: 'json',
    });
    const _openid = res.data.openid
    var sessionKey = res.data.session_key
    var pc = new WXBizDataCrypt(appID, sessionKey)
    var user_data = pc.decryptData(encryptedData, iv)
    user_data.watermark.timestamp = moment(user_data.watermark.timestamp * 1000).format("YYYY-MM-DD HH:mm:ss")
    user_data.nickName = new Buffer(user_data.nickName)
    user_data.nickName = user_data.nickName.toString('base64')
    const _data = yield ctx.service.user.find_wechat_user(user_data.openId)
    if (_data.length) {//这里做判断 如果有从数据库获取到数据 说明是老用户 就更新用户登录历史表然后查询用户余额表 并把用户的余额信息返回给前台
        const result_Landing_History = yield ctx.service.user.insert_Landing_History(user_data.openId, user_data.nickName, user_data.watermark.timestamp)
        const result_Recharge_user = yield ctx.service.user.find_Recharge_user( _openid)
        ctx.body = result_Recharge_user
    } else {//如果没有从数据库获取到数据  说明是新用户 在用户信息表和用户余额表中增加信息
        const result_insert_wechat_user = yield ctx.service.user.insert_wechat_user({
            openID: _openid,
            nickName: user_data.nickName,
            gender: user_data.gender,
            language: user_data.language,
            city: user_data.city,
            province: user_data.province,
            country: user_data.country,
            avatarUrl: user_data.avatarUrl,
            time_stamp: user_data.watermark.timestamp,
            appID: user_data.watermark.appid,
        });
        const result_insert_Recharge_user = yield ctx.service.user.insert_Recharge_user({
            openID: _openid,
            balance: "0",
            total_consumption: "0"
        })
        const result_Recharge_user = yield ctx.service.user.find_Recharge_user( _openid)
        

        ctx.body = result_Recharge_user 
    }

};